import {asyncRouterHandle} from '@/utils/asyncRouter'
import {asyncMenu} from '@/api/menu'
import {defineStore} from 'pinia'
import {ref} from 'vue'

// Helper function to format and process the routers
function formatRouter(routes, routerList, keepAliveRouters) {
    if (routes) {
        routes.forEach(item => {
            // Add route to routerList if it's not hidden and has no hidden children
            if (!item.hidden && (!item.children || !item.children.every(child => child.hidden)) && item.name !== '404') {
                routerList.push({label: item.meta.title, value: item.name})
            }
            item.meta.hidden = item.hidden

            // Check if the component property is a function or an object
            const isAsyncComponent = typeof item.component === 'function';

            // Add component to keepAliveRouters if it or any of its children should be kept alive
            if (item.children && item.children.some(child => child.meta.keepAlive) || item.meta.keepAlive) {

                if (isAsyncComponent) {
                    item.component().then(val => {
                        keepAliveRouters.push(val.default ? val.default.name : val.name)
                    });
                } else {
                    const componentName = item.component.name;
                    keepAliveRouters.push(componentName);
                }
            }

            if (item.children && item.children.length > 0) {
                formatRouter(item.children, routerList, keepAliveRouters)
            }
        })
    }
}

export const useRouteStore = defineStore('route', () => {
    const asyncRouters = ref([])
    const routerList = ref([])
    const keepAliveRouters = ref([])

    async function SetAsyncRouter() {
        try {
            const baseRouter = [{
                path: '/layout',
                name: 'layout',
                component: 'view/layout/index.vue',
                meta: {
                    title: '底层layout'
                },
                children: []
            }]
            const asyncRouterRes = await asyncMenu()
            const asyncRouter = asyncRouterRes.data.menus
            asyncRouter.push({
                path: '404',
                name: '404',
                hidden: true,
                meta: {
                    title: '迷路了*。*',
                },
                component: 'view/error/index.vue'
            })

            console.log(asyncRouter)
            // Format the asyncRouter data and update the lists
            formatRouter(asyncRouter, routerList.value, keepAliveRouters.value)

            // Assign formatted asyncRouter as children to the baseRouter
            baseRouter[0].children = asyncRouter

            // Add catch-all route for 404
            baseRouter.push({
                path: '/:catchAll(.*)',
                redirect: '/layout/404'
            })


            // Apply the async routers to the router system
            asyncRouterHandle(baseRouter)
            asyncRouters.value = baseRouter
        } catch (error) {
            console.error('Error setting async router:', error)
        }
    }

    return {
        asyncRouters,
        routerList,
        keepAliveRouters,
        SetAsyncRouter
    }
})